﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Opennav.MapGenerator.Map.Labels;
using System.Diagnostics;
using System.IO;
using Opennav.MapGenerator.Map.MapTiles;
using Opennav.MapGenerator.Locator;

namespace Opennav.MapGenerator.Map.Locations
{
    public class City
    {
        private int _index = -1;
        private List<MapPoint> _mapPoints = new List<MapPoint>();

        public City(GeoPlace place, Region region, Label label)
        {
            this.Place = place;
            this.Region = region;
            this.Label = label;
        }

        public City(GeoPlace place, City parentCity, Region region, Label label)
        {
            this.Place = place;
            this.Region = region;
            this.ParentCity = parentCity;
            this.Label = label;
        }

        public int Id
        {
            get
            {
                Debug.Assert(_index >= 0);
                return _index;
            }
            set
            {
                this._index = value;
            }
        }

        public GeoPlace Place { get; private set; }

        public Region Region { get; private set; }

        public City ParentCity { get; private set; }

        public Label Label { get; private set; }

        public MapPoint MapPoint { get; set; }

        public void Write1(Stream stream)
        {
            BinaryWriter writer = new BinaryWriter(stream);
            writer.Write((uint)(Label.Offset & 0x7fffffff));
            writer.Write((ushort)(Region.Id & 0x7fff));
            int parentCityId = -1;
            if (ParentCity != null)
                parentCityId = ParentCity.Id;
            writer.Write((byte)(parentCityId & 0xff));
            writer.Write((short)(parentCityId >> 8));
            ushort tileId = 0;
            ushort objectId = 0;
            writer.Write(objectId);
            writer.Write(tileId);
        }

        public void Write2(Stream stream)
        {
            stream.Seek(9, SeekOrigin.Current);
            BinaryWriter writer = new BinaryWriter(stream);
            MapReference reference = MapPoint.References.Last();
            writer.Write(reference.ObjectId);
            writer.Write(reference.TileId);
        }
    }
}
